package com.yls.except.filter;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yls.except.task.RedisCash;
import com.yls.except.util.*;

/**
 * 全局过滤器
 * 
 * @作用 更新每个用户操作时间
 * @author xusheng
 * @time 2015-7-13 上午9:14:59
 * @version 1.0
 * @Description: {}
 * 
 */

public class Glodalfilter implements Filter {
	@SuppressWarnings("unused")
	private FilterConfig filterConfig;

	public void destroy() {
		filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		String json = req.getParameter("json");
		if(StringIsempty.isallempty(json)) {
			chain.doFilter(req, resp);
			return;
		}
		Map<String, Object> map = GeneralResult.jsonStrToMap(json);
		if(map == null) {
			chain.doFilter(req, resp);
			return;
		}
		String token = map.get("token") + "";
		if(!StringIsempty.isallempty(token)) {
			long timestamp = new Date().getTime();
			String item = ImgProperties.getConstan("itemname");
			token = HexString.decode(token);
			token = HexString.removestr(token, 6, item, "");
			Map<String, String> usermap = RedisCash.getMap(token);
			if(!StringIsempty.isNullMap(usermap)) {
				String uid = usermap.get("uid");
				String type = usermap.get("type");
				String openid = usermap.get("openid");
				if(!StringIsempty.isallempty(uid)) {
					Long datetime = Long.parseLong(usermap.get("time"));
					Long mistaketime = timestamp - datetime;
					double time = mistaketime / 1000 / 60 / 60 / 24;
					if (time < ConstantUtil.LONGTIME) {
						req.setAttribute("uid", uid);
						req.setAttribute("type", type);
						req.setAttribute("openid", openid);
						usermap.put("time", timestamp + "");
						RedisCash.redisMap(token, usermap);
					}
				}
			}
		}
		chain.doFilter(req, resp);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

}
